<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>加载声音</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      /* 隐藏body窗口区域滚动条 */
    }
  </style>
  <!--引入three.js三维引擎-->
  <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
  <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/examples/js/controls/OrbitControls.js"></script>
  <!-- <script src="./three.js"></script> -->
  <!-- <script src="http://www.yanhuangxueyuan.com/threejs/build/three.js"></script> -->
</head>

<body>
  <input type="range" name="slider" min="1" max="100" step="1" value="0" style="position: absolute; top: 10px;left: 10px;"/>
  <script src="static/js/main.js"></script>
  <script>
    /**
     * 创建场景对象Scene
     */
    let scene = new THREE.Scene();
    
    let mesh = genMesh(() => {
      let geometry = new THREE.BoxGeometry(100, 100, 100)
    
      let mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
        color: 0x44dd44,
        side: THREE.DoubleSide,
      })); //网格模型对象
      return mesh
    })
    scene.add(mesh); //网格模型添加到场景中



    let axisHelper = new THREE.AxesHelper(250);
    scene.add(axisHelper);
    /**
     * 光源设置
     */
    //点光源
    let point = new THREE.PointLight(0xffffff);
    point.position.set(400, 200, 300); //点光源位置
    scene.add(point); //点光源添加到场景中
    //环境光
    let ambient = new THREE.AmbientLight(0x888888);
    scene.add(ambient);
    // console.log(scene)
    // console.log(scene.children)
    /**
     * 相机设置
     */
    let width = window.innerWidth; //窗口宽度
    let height = window.innerHeight; //窗口高度
    let k = width / height; //窗口宽高比
    let s = 200; //三维场景显示范围控制系数，系数越大，显示的范围越大
    //创建相机对象
    let camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    // camera = new THREE.PerspectiveCamera(60, k, 1, 1000)
    camera.position.set(0, 200, 600); //设置相机位置
    camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

    // let points = []
    // for (let i = 0; i < 128; ++i) {
    //     points.push(i * 10)
    //     points.push(0)
    //     points.push(0)
    // }
    // let vertices = new Float32Array(poin ts)
    // let geometry = new THREE.BufferGeometry()
    // geometry.attributes.position = new THREE.BufferAttribute(vertices, 3)
    let geometry = new THREE.Geometry()
    let arc = new THREE.ArcCurve(0, 0, 200, 0, 2 * Math.PI)
    geometry.setFromPoints(arc.getPoints(256))
    let line=new THREE.Line(geometry, new THREE.LineBasicMaterial({
        // 线条颜色
        color:0x44ffff,
        // 线宽 
        linewidth: 2,
    }));//线条模型对象
    line.rotateX(Math.PI / 2)
    line.position.y = 50
    scene.add(line);//线条对象添加到场景中
    
    let listener = new THREE.AudioListener()
    let audio = new THREE.Audio(listener)
    let audioLoader = new THREE.AudioLoader()
    audioLoader.load("static/audio/儿童歌曲 - 童年.mp3", buffer => {
      audio.setBuffer(buffer)
      audio.setLoop(true)
      audio.setVolume(0.5)
    //   audio.play()
      analyser = new THREE.AudioAnalyser(audio)
    })
    
    // camera.add(listener)
    // let positionalAudio = new THREE.PositionalAudio(listener)
    // mesh.add(positionalAudio)
    // audioLoader = new THREE.AudioLoader()
    // audioLoader.load("static/audio/儿童歌曲 - 童年.mp3", buffer => {
    //   positionalAudio.setBuffer(buffer)
    //   positionalAudio.setLoop(true)
    //   positionalAudio.setVolume(0.9)
    //   positionalAudio.setRefDistance(200)
    //   positionalAudio.play()
    // })

    /**
     * 创建渲染器对象
     */
    let renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);//设置渲染区域尺寸
    renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
    document.body.appendChild(renderer.domElement); //body元素中插入canvas对象
    
    window.onresize = function() {
        let width = window.innerWidth; //窗口宽度
        let height = window.innerHeight; //窗口高度
        renderer.setSize(width, height);//设置渲染区域尺寸
        
        k = width / height; //窗口宽高比
        //修改相机对象属性
        camera.left = -s * k
        camera.right = s * k
        camera.top = s
        camera.bottom = -s
        camera.aspect = k
        camera.updateProjectionMatrix ()
    }
    
    Game = {
		tickLength: 16, 				// 20Hz
		lastTick: performance.now(),	// 最后更新时间
		stopKey: 0,
		canvas: null,
		context: null,
	}
	// 创建一个时钟对象Clock
    let clock = new THREE.Clock()
    let analyser = null
    function render(tFrame) {
        if (tFrame === undefined) {
            tFrame = performance.now()
            Game.lastTick = performance.now()
        }
        let nextTick = Game.lastTick + Game.tickLength
        let tickNum = 0
        if (tFrame > nextTick) {
            tickNum = Math.floor((tFrame - Game.lastTick) / Game.tickLength)
        }
        Game.lastTick = tFrame
        // clock.getDelta()方法获得两帧的时间间隔
        // mixer.update(clock.getDelta())
        if (analyser) {
            let frequency = analyser.getAverageFrequency()
            // mesh.scale.y = 1 + 5 * frequency / 256
            mesh.geometry.vertices.forEach(v => {
                if (v.y > 0) {
                    v.y = 50 + 100 * frequency / 100
                }
            })
            mesh.geometry.verticesNeedUpdate = true
            
            let data = analyser.getFrequencyData()
            // let arrs = line.geometry.attributes.position.array
            // for(let i = 0, l = arrs.length; i < l; i+=3) {
            //     // if (i == 0 || i == l - 3) continue
            //     arrs[i+1] = 50 * data[i] / 80
            // }
            // https://wow.techbrood.com/fiddle/28106
            // line.geometry.attributes.position.needsUpdate = true
            let arrs = line.geometry.vertices
            for(let i = 0, l = arrs.length; i < l; ++i) {
                if (i == l - 1) {
                    arrs[i].z = arrs[0].z
                    continue
                }
                arrs[i].z = -50 * data[i] / 80
            }
            // line.geometry.vertices.forEach((v1, i) => {
            //     // v1.y = 50 * data[i] / 80
            //     if (i > 0 & i !== line.geometry.vertices - 1) {
            //         v1.z = -50 * data[i] / 80
            //     }
            // })
            line.geometry.verticesNeedUpdate = true



        }
        //执行渲染操作   指定场景、相机作为参数
        renderer.render(scene, camera);
        Game.stopKey = requestAnimationFrame(render)
    }
    document.onkeydown = function (e) {
        e = e || window.event;  //标准化事件对象
        let t = e.target || e.srcElement;  //获取发生事件的元素，兼容IE和DOM
        if (e.code == "Space") {  // 按下空格键 开始/暂停
            if (audio.isPlaying) {
                audio.stop()
            } else {
                audio.play()
            }
            console.log("audio: " + audio.isPlaying)
        }
        console.log(e.code)
    }
    function getV(distance) {
        let g = 0.5
        let t = Math.sqrt(distance * 2 / 9)
        return g * t
    }
    render()
    let controls = new THREE.OrbitControls(camera,renderer.domElement);//创建控件对象
    // controls.addEventListener('change', render);
</script>
</body>
</html>
